<?php
// +----------------------------------------------------------------------
// Csmmeet [ CSM系列公共源码 ]
// Author: chensm <chenshiming0802@163.com>
// Create by chensm at 2020-02-26
// +----------------------------------------------------------------------
namespace addons\csmtable\library;

use think\Config;
use think\Request;
use think\Response;
use think\Url;
use think\View as ViewTemplate;
use think\exception\HttpResponseException;

class CsmUtils
{

    /**
     * 根据dao的select内容匹配到现有的list中,keyname为匹配对象
     */
    public static function fillListColumn(&$list, $fieldname, $daoselect, $daoselectfieldname)
    {
        $keyvalues = [];
        foreach ($list as $item) {
            $keyvalues[] = $item->$fieldname;
        }
        $newlist = $daoselect->where($daoselectfieldname, 'in', $keyvalues)->select();
        // echo $dao->getLastSql();
        $newlist2 = [];
        foreach ($newlist as $item) {
            $newlist2[$item->$daoselectfieldname] = $item;
        }
        foreach ($list as $k => $item) {
            if (isset($newlist2[$item->$fieldname])) {
                $list[$k] = array_merge(json_decode($newlist2[$item->$fieldname], true), json_decode($item, true));
            }
        }
    }

    /**
     * 转换list中的id字段,(根据dao中的表id对应的name)
     * 通常用于查询列表中用
     */
    public static function convertListColumn(&$list, $fieldname, $dao, $daokeyname = 'name')
    {
        $ids = [];
        foreach ($list as $item) {
            $ids[] = $item->$fieldname;
        }
        $keylist = $dao->where("id", "in", $ids)
            ->field("id,{$daokeyname}")
            ->select();
        // echo $dao->getLastSql();
        $keynames = [];
        foreach ($keylist as $keyrow) {
            $keynames['D' . $keyrow->id] = $keyrow->$daokeyname;
        }
        // var_dump($keynames);
        foreach ($list as $i => $item) {
            if (array_key_exists('D' . $item->$fieldname, $keynames)) {
                $list[$i][$fieldname] = $keynames['D' . $item->$fieldname];
            } else {
                $list[$i][$fieldname] = '';
            }
        }
    }

    /**
     * 邮件发送
     */
    public static function notifyUser($email, $title, $content)
    {
        $site = Config::get("site");
        $obj = \app\common\library\Email::instance();
        $obj->to($email)
            ->subject("[" . $site['name'] . "]" . $title)
            ->message($content)
            ->send();
    }

    public static function isNullOrBlank($str)
    {
        if ($str == null || $str == "") {
            return true;
        } else {
            return false;
        }
    }

    public static function unescape($str)
    {
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i ++) {
            if ($str[$i] == '%' && $str[$i + 1] == 'u') {
                $val = hexdec(substr($str, $i + 2, 4));
                if ($val < 0x7f)
                    $ret .= chr($val);
                else if ($val < 0x800)
                    $ret .= chr(0xc0 | ($val >> 6)) . chr(0x80 | ($val & 0x3f));
                else
                    $ret .= chr(0xe0 | ($val >> 12)) . chr(0x80 | (($val >> 6) & 0x3f)) . chr(0x80 | ($val & 0x3f));
                $i += 5;
            } else if ($str[$i] == '%') {
                $ret .= urldecode(substr($str, $i, 3));
                $i += 2;
            } else
                $ret .= $str[$i];
        }
        return $ret;
    }

    /**
     * Copy from traits\controller\Jump.php#error function
     */
    public static function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = Request::instance()->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ('' !== $url && ! strpos($url, '://') && 0 !== strpos($url, '/')) {
            $url = Url::build($url);
        }

        $type = Request::instance()->isAjax() ? Config::get('default_ajax_return') : Config::get('default_return_type');

        $result = [
            'code' => 0,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait
        ];

        if ('html' == strtolower($type)) {
            $template = Config::get('template');
            $view = Config::get('view_replace_str');

            $result = ViewTemplate::instance($template, $view)->fetch(Config::get('dispatch_error_tmpl'), $result);
        }

        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }

    /**
     * Copy from traits\controller\Jump.php#success function
     */
    public static function success($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        if (is_null($url) && ! is_null(Request::instance()->server('HTTP_REFERER'))) {
            $url = Request::instance()->server('HTTP_REFERER');
        } elseif ('' !== $url && ! strpos($url, '://') && 0 !== strpos($url, '/')) {
            $url = Url::build($url);
        }

        $type = Request::instance()->isAjax() ? Config::get('default_ajax_return') : Config::get('default_return_type');
        $result = [
            'code' => 1,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait
        ];

        if ('html' == strtolower($type)) {
            $template = Config::get('template');
            $view = Config::get('view_replace_str');

            $result = ViewTemplate::instance($template, $view)->fetch(Config::get('dispatch_success_tmpl'), $result);
        }

        $response = Response::create($result, $type)->header($header);
        
        throw new HttpResponseException($response);
    }
}